// 2025/11/15
// 二叉树的右视图

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> rightSideView(TreeNode* root) {
        vector<int> ans;
        if(!root) return ans;
        queue<pair<TreeNode*, int>> q;
        q.emplace(root, 0);
        while(!q.empty())
        {
            auto [cur, level] = q.front();
            q.pop();
            if(cur->left)
                q.emplace(cur->left, level + 1);
            if(cur->right)
                q.emplace(cur->right, level + 1);
            // 该行最后一个
            if(q.empty() || q.front().second != level)
                ans.emplace_back(cur->val);
        }
        return ans;
    }
};